package com.light.springboot.base.jpa.repostitory.support;

import com.light.springboot.base.jpa.BeanTransformerAdapter;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.util.Assert;

import javax.persistence.*;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * dao的封装类.
 * 
 * <pre>
 *  封装一些涉及到原生sql的增删改查分页等功能
 * </pre>
 * 
 * @author 杨雷
 * @since 1.0
 *
 */
public class BaseRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseRepository<T, ID> {

    //父类没有不带参数的构造方法，这里手动构造父类
    public BaseRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
        super(domainClass, entityManager);
        System.out.println("构造函数" + domainClass);
        this.entityManager = entityManager;
        this.entityClass = domainClass;
    }

    @PersistenceContext
    private EntityManager entityManager;

    private Class<T> entityClass;

    @Override
    public EntityManager getEntityManager() {
        return entityManager;
    }

    @Override
    public T findOne(ID id, LockModeType lockMode) {
        return entityManager.find(getDomainClass(), id, lockMode);
    }

    @Override
    public T findOne(Specification<T> spec, LockModeType lockMode) {
        try {
            return getQuery(spec, (Sort) null).setLockMode(lockMode).getSingleResult();
        } catch (NoResultException T) {
            return null;
        }
    }

    @Override
    public List<T> findTop(int top, Specification<T> spec, Sort sort) {
        return findTop(top, spec, sort, LockModeType.NONE);
    }

    @Override
    public List<T> findTop(int top, Specification<T> spec, Sort sort, LockModeType lockMode) {
        return getQuery(spec, sort).setLockMode(lockMode).setMaxResults(top).getResultList();
    }

    @Override
    public <S extends T> S update(S entity) {
        Session session = entityManager.unwrap(Session.class);
        session.update(entity); //使用update方法提高效率
        return entity;
    }

    @Override
    public int updateByHQL(String hql, Map<String, Object> parameters) {
        Query query = entityManager.createQuery(hql);
        if (parameters != null) {
            Iterator<Map.Entry<String, Object>> it = parameters.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                query.setParameter(entry.getKey(), entry.getValue());
            }
        }
        return query.executeUpdate();
    }

	/*@SuppressWarnings("unchecked")
    @Override
	public <T> List<T> nativeSqlResultDTO(Class<T> dtoClass, String sql, final Map<String, Object> params) {
		return nativeSqlResultDTO(dtoClass, sql, params, null);
	}*/

    @SuppressWarnings("unchecked")
    public <T> List nativeSqlResult(String sql, final Map<String, Object> params) {
        Query query = entityManager.createNativeQuery(sql);
        if (null != params && params.size() > 0) {
            for (String key : params.keySet()) {
                query.setParameter(key, params.get(key));
            }
        }
        return query.getResultList();
    }

    @Override
    public int updateNativeSql(String sql, Map<String, Object> parameters) {
        Query query = entityManager.createNativeQuery(sql);
        if (parameters != null) {
            Iterator<Map.Entry<String, Object>> it = parameters.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                query.setParameter(entry.getKey(), entry.getValue());
            }
        }
        return query.executeUpdate();
    }

    /**
     * 查询分页的方法.
     * <pre>
     *  带着条件进行动态拼接sql的查询方法
     * </pre>
     * 
     */
    @Override
    public HashMap<String, Object> sqlQuery(String queryString, String countSql, Map<String, ?> values, int offset,
            int limit, String countName, String rowsName) {

        Assert.hasText(queryString, "queryString不能为空");

        HashMap<String, Object> map = new HashMap<String, Object>();

        Query query = entityManager.createNativeQuery(queryString);
        Query countQuery = entityManager.createNativeQuery(countSql);

        //给条件赋上值
        if (values != null && !values.isEmpty()) {
            for (Map.Entry<String, ?> entry : values.entrySet()) {  
                query.setParameter(entry.getKey(), entry.getValue());
                countQuery.setParameter(entry.getKey(), entry.getValue());    
            } 
        }

        query.setFirstResult(offset);
        query.setMaxResults(limit);
        query.unwrap(SQLQuery.class).setResultTransformer(new BeanTransformerAdapter(this.entityClass));

        Object results = query.getResultList();
        Object resultsCount = countQuery.getSingleResult();

        map.put(countName, resultsCount);
        map.put(rowsName, results);

        return map;
    }

    @Override
    public List sqlQuery(String queryString, Map<String, ?> values) {
        Session session = entityManager.unwrap(org.hibernate.Session.class);
        SQLQuery query = session.createSQLQuery(queryString);

//      //给条件赋上值
//      if (values != null && !values.isEmpty()) {
//          for (Map.Entry<String, ?> entry : values.entrySet()) {  
//              query.setParameter(entry.getKey(), entry.getValue());
//          } 
//      }

        if (values != null) {
            query.setProperties(values);
          }

        query.setResultTransformer(new BeanTransformerAdapter(this.entityClass));

        return query.list();
    }

    @Override
    public List sqlQuery(String queryString, Object... values) {
        Query query = entityManager.createNativeQuery(queryString);
//      Session session = entityManager.unwrap(org.hibernate.Session.class);
//      SQLQuery query = session.createSQLQuery(queryString);


        if (values != null) {
            for (int i = 0; i < values.length; i++) {
              query.setParameter(i + 1, values[i]);
            }
          }

        query.unwrap(SQLQuery.class).setResultTransformer(new BeanTransformerAdapter(this.entityClass));

        return query.getResultList();
    }

    @Override
    public HashMap<String, Object> retrieve(String queryString, String countHql, Map<String, ?> values, int offset,
            int limit, String countName, String rowsName) {

        HashMap<String, Object> map = new HashMap<String, Object>();

        Query query = entityManager.createQuery(queryString);
        Query countQuery = entityManager.createQuery(countHql);

        //给条件赋上值
        if (values != null && !values.isEmpty()) {
            for (Map.Entry<String, ?> entry : values.entrySet()) {  
                query.setParameter(entry.getKey(), entry.getValue());
                countQuery.setParameter(entry.getKey(), entry.getValue());    
            } 
        }

        query.setFirstResult(offset);
        query.setMaxResults(limit);

        Object results = query.getResultList();
        Object resultsCount = countQuery.getSingleResult();

        map.put(countName, resultsCount);
        map.put(rowsName, results);

        return map;
    }
}